package com.fjwt.gz.service.activity.platform.acte002;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjwt.gz.core.cache.RedisUtil;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.db.bo.ActivityAwardAndSettingBo;
import com.fjwt.gz.db.bo.ActivityUserTimesBO;
import com.fjwt.gz.db.dto.FansActivityDTO;
import com.fjwt.gz.db.entity.ActivityAwardEntity;
import com.fjwt.gz.db.entity.ActivityEntity;
import com.fjwt.gz.db.entity.AgentInfoEntity;
import com.fjwt.gz.db.entity.AwardCouponEntity;
import com.fjwt.gz.db.entity.FansAwardEntity;
import com.fjwt.gz.db.vo.ActivityAwardVO;
import com.fjwt.gz.service.activity.BaseActivityDTO;
import com.fjwt.gz.service.activity.BaseActivityService;
import com.fjwt.gz.service.impl.ActivityAwardService;
import com.fjwt.gz.service.impl.ActivityService;
import com.fjwt.gz.service.impl.ActivitySettingService;
import com.fjwt.gz.service.impl.AgentInfoService;
import com.fjwt.gz.service.impl.AwardCouponService;
import com.fjwt.gz.service.impl.AwardGoodsService;
import com.fjwt.gz.service.impl.AwardSettingService;
import com.fjwt.gz.service.impl.FansAwardService;
import com.fjwt.gz.service.impl.SendAwardService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 越来越邮喜活动
 *
 * @Author Will
 * @date 2023-12-19
 */
@Slf4j
@Service
public class ACTE002Service extends BaseActivityService<Object> {

    private static String logPrefix = "【A/B/C券活动】";

    @Autowired
    private ActivityAwardService activityAwardService;

    @Autowired
    private FansAwardService fansAwardService;

    @Autowired
    private AwardCouponService awardCouponService;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private SendAwardService sendAwardService;

    @Autowired
    private AwardGoodsService awardGoodsService;

    @Autowired
    private AwardSettingService awardSettingService;

    @Autowired
    private ActivitySettingService activitySettingService;
    @Autowired
    private AgentInfoService agentInfoService;


    /**
     * 新建活动
     */
    @Override
    public void add(BaseActivityDTO activityDTO) {
        log.info("新增ACTE002的活动");
        super.add(activityDTO);
    }

    /**
     * 修改活动
     */
    @Override
    public void update(BaseActivityDTO activityDTO) {
        log.info("更新ACTE002的活动");
        super.update(activityDTO);
    }

    /**
     * 删除活动
     */
    @Override
    public void delete(Long activityId) {
        log.info("删除ACTE002的活动");
        super.delete(activityId);
    }

    /**
     * 活动详情--pc
     */
    @Override
    public BaseActivityDTO detail(Long activityId) {
        log.info("查看ACTE002的活动详情");
        BaseActivityDTO baseActivityDetailsVO = super.detail(activityId);
        return baseActivityDetailsVO;
    }

    @Override
    public void realNameAfter(JSONObject jsonObject) {
        //长春活动发放实名待激活的奖品B券
        log.info("{}，参数信息：{}", logPrefix, jsonObject.toJSONString());
        Long fansId = jsonObject.getLong("fansId");
        String appId = jsonObject.getString("appId");
        Long activityId = jsonObject.getLong("activityId");
        Long activityChannelId = jsonObject.getLong("activityChannelId");
        String locationAgentNo = jsonObject.getString("locationAgentNo");
        AgentInfoEntity agentInfo = agentInfoService.getAgentInfo(locationAgentNo);

        // 获取活动奖品配置信息
        List<ActivityAwardAndSettingBo> activityAwardList = awardSettingService.getActivityAwardList(activityId, redisOutTime);
        if (activityAwardList == null || activityAwardList.isEmpty()) {
            throw new BizException("活动奖品配置信息有误");
        }
        for (ActivityAwardAndSettingBo a : activityAwardList) {
            if ("B".equals(a.getRemark())) {
                sendAward(fansId, appId, activityChannelId, a, activityEntity.getEndTime(), agentInfo);
            }
        }
    }

    @Override
    public void realNameAfter(FansAwardEntity fansAwardEntity) {
        log.info("ACTE002,实名认证后的逻辑进来的信息：{}", JSONUtil.toJsonStr(fansAwardEntity));
        if (fansAwardEntity.getState() != 3) {
            return;
        }
        if (!"B".equals(fansAwardEntity.getRemark())) {
            return;
        }

        //查询活动
        LambdaQueryWrapper<ActivityAwardEntity> gw = ActivityAwardEntity.gw();
        gw.eq(ActivityAwardEntity::getAwardId, fansAwardEntity.getAwardId());
        gw.eq(ActivityAwardEntity::getAwardType, 0);
        ActivityAwardEntity activityAwardEntity = activityAwardService.getOne(gw);
        log.info("活动奖品信息:{}", JSONUtil.toJsonStr(activityAwardEntity));
        ActivityEntity activityEntity = activityService.getById(activityAwardEntity.getActivityId());
        log.info("活动信息：{}", JSONUtil.toJsonStr(activityEntity));

        //卡券及配置信息
        ActivityAwardAndSettingBo activityAwardAndSettingBo = activityAwardService.getActivityAndApp(fansAwardEntity.getAwardId(), fansAwardEntity.getAwardType());
        log.info("卡券信息：{}", JSON.toJSONString(activityAwardAndSettingBo));
        // 激活奖品
        Long fansAwardId = sendAwardService.autoActivateAward(fansAwardEntity, activityAwardAndSettingBo, activityEntity.getAgentNo());
//        发送公众号消息
        AwardCouponEntity awardCouponEntity = awardCouponService.getById(fansAwardEntity.getAwardId());
        sendAwardService.sendActivateCouponMsg(activityEntity.getActivityId(), fansAwardEntity.getFansId(), fansAwardId, awardCouponEntity.getCouponId(), activityEntity.getActivityName(), awardCouponEntity.getCouponName());
    }

    @Override
    public JSONObject getActivityAwards(FansActivityDTO fansActivityDTO) {
        JSONObject json = new JSONObject();
        ActivityEntity activityEntity = activityService.getById(fansActivityDTO.getActivityId());
        if (ObjectUtils.isEmpty(activityEntity)) {
            throw new BizException("活动异常，请重试");
        }
        // 查询活动奖品关联配置
        List<ActivityAwardAndSettingBo> activityAwardList = awardSettingService.getActivityAwardList(fansActivityDTO.getActivityId(), activityEntity.getEndTime().getTime() - DateUtil.date().getTime());
        if (activityAwardList.isEmpty()) {
            throw new BizException("该活动未配置奖品！");
        }
        log.info("活动配置奖品信息：{}", JSONObject.toJSONString(activityAwardList));
        JSONObject couponA = new JSONObject();
        JSONObject couponB = new JSONObject();
        JSONObject couponC = new JSONObject();
        JSONObject couponD = new JSONObject();
        JSONObject couponE = new JSONObject();
        JSONObject couponF = new JSONObject();
        for (ActivityAwardAndSettingBo a : activityAwardList) {
            if ("A".equals(a.getRemark())) {
                couponA.put("awardId", a.getAwardId());
                couponA.put("awardType", a.getAwardType());
                couponA.put("remark", a.getRemark());
                FansAwardEntity entity = this.selectOneFansAward(fansActivityDTO, a);
                log.info("用户领取奖品A券详情信息：{}", JSONObject.toJSONString(entity));
                if (null == entity) {
                    couponA.put("state", 0);
                } else {
                    couponA.put("state", entity.getState());
                    couponA.put("fansAwardId", entity.getFansAwardId());
                }
                couponA.put("awardAliasName", a.getAwardName());
                couponA.put("awardAliasPrice", a.getAwardPrice());
            } else if ("B".equals(a.getRemark())) {
                couponB.put("awardId", a.getAwardId());
                couponB.put("awardType", a.getAwardType());
                couponB.put("remark", a.getRemark());
                FansAwardEntity entity = this.selectOneFansAward(fansActivityDTO, a);
                log.info("用户领取奖品B券详情信息：{}", JSONObject.toJSONString(entity));
                if (null == entity) {
                    couponB.put("state", 0);
                } else {
                    couponB.put("state", entity.getState());
                    couponB.put("fansAwardId", entity.getFansAwardId());
                }
                couponB.put("awardAliasName", a.getAwardName());
            } else if ("C".equals(a.getRemark())) {
                couponC.put("awardId", a.getAwardId());
                couponC.put("awardType", a.getAwardType());
                couponC.put("remark", a.getRemark());
                FansAwardEntity entity = this.selectOneFansAward(fansActivityDTO, a);
                log.info("用户领取奖品C详情信息：{}", JSONObject.toJSONString(entity));
                if (null == entity) {
                    couponC.put("state", 0);
                } else {
                    couponC.put("state", entity.getState());
                    couponC.put("fansAwardId", entity.getFansAwardId());
                }
                couponC.put("awardAliasName", a.getAwardName());
            } else if ("D".equals(a.getRemark())) {
                couponD.put("awardId", a.getAwardId());
                couponD.put("awardType", a.getAwardType());
                couponD.put("remark", a.getRemark());
                FansAwardEntity entity = this.selectOneFansAward(fansActivityDTO, a);
                log.info("用户领取奖品D券详情信息：{}", JSONObject.toJSONString(entity));
                if (null == entity) {
                    couponD.put("state", 0);
                } else {
                    couponD.put("state", entity.getState());
                    couponD.put("fansAwardId", entity.getFansAwardId());
                }
                couponD.put("awardAliasName", a.getAwardName());
            } else if ("E".equals(a.getRemark())) {
                couponE.put("awardId", a.getAwardId());
                couponE.put("awardType", a.getAwardType());
                couponE.put("remark", a.getRemark());
                FansAwardEntity entity = this.selectOneFansAward(fansActivityDTO, a);
                log.info("用户领取奖品E详情信息：{}", JSONObject.toJSONString(entity));
                if (null == entity) {
                    couponE.put("state", 0);
                } else {
                    couponE.put("state", entity.getState());
                    couponE.put("fansAwardId", entity.getFansAwardId());
                }
                couponE.put("awardAliasName", a.getAwardName());
            } else if ("F".equals(a.getRemark())) {
                couponF.put("awardId", a.getAwardId());
                couponF.put("awardType", a.getAwardType());
                couponF.put("remark", a.getRemark());
                FansAwardEntity entity = this.selectOneFansAward(fansActivityDTO, a);
                log.info("用户领取奖品F详情信息：{}", JSONObject.toJSONString(entity));
                if (null == entity) {
                    couponF.put("state", 0);
                } else {
                    couponF.put("state", entity.getState());
                    couponF.put("fansAwardId", entity.getFansAwardId());
                }
                couponF.put("awardAliasName", a.getAwardName());
            }
        }
        json.put("A", couponA);
        json.put("B", couponB);
        json.put("C", couponC);
        json.put("D", couponD);
        json.put("E", couponE);
        json.put("F", couponF);
        log.info("用户fansId：{}，【越减越便宜】用户领取奖品情况：{}", fansActivityDTO.getFansId(), json.toJSONString());
        return json;
    }

    /**
     * 查询用户领取的最后一张卡券
     * @param fansActivityDTO
     * @param activityAwardAndSettingBo
     * @return
     */
    private FansAwardEntity selectOneFansAward(FansActivityDTO fansActivityDTO, ActivityAwardAndSettingBo activityAwardAndSettingBo) {
        return fansAwardService.getOne(FansAwardEntity.gw()
                .eq(FansAwardEntity::getFansId, fansActivityDTO.getFansId())
                .eq(FansAwardEntity::getAwardId, activityAwardAndSettingBo.getAwardId())
                .eq(FansAwardEntity::getAwardType, activityAwardAndSettingBo.getAwardType())
                .eq(FansAwardEntity::getRemark, activityAwardAndSettingBo.getRemark())
                .orderByDesc(FansAwardEntity::getCreatedAt)
                .last("limit 1"));
    }

    /**
     * 参与活动  长春 越来越邮喜活动
     */
    @Override
    public ActivityAwardVO takePartIn(FansActivityDTO fansActivityDTO) {
        super.takePartIn(fansActivityDTO);

        Long activityId = fansActivityDTO.getActivityId();
        Long fansId = fansActivityDTO.getFansId();
        String appId = fansActivityDTO.getAppId();
        Long activityChannelId = fansActivityDTO.getActivityChannelId();

        AgentInfoEntity agentInfoEntity = agentInfoService.getAgentInfo(fansActivityDTO.getLocationAgentNo());

        // 检测用户参与限制条件
        JSONObject limitJson = activitySettingService.checkActivitySetting(fansEntity, fansActivityDTO.getAppId(), redisOutTime, activityEntity);

        //      检测活动奖品配置
        // 获取活动奖品
        List<ActivityAwardAndSettingBo> activityAwardList = awardSettingService.getActivityAwardList(activityId, redisOutTime);
        // 校验用户奖品限制
        Map<Long, JSONObject> awardUserTimesJsonMap = new HashMap<>();
        for (ActivityAwardAndSettingBo activityAwardAndSettingBo : activityAwardList) {
            JSONObject awardUserTimesJson = awardSettingService.AwardSettingRule(fansId, activityEntity.getAgentNo(), activityAwardAndSettingBo);
            if (ObjectUtils.isNotEmpty(awardUserTimesJson)) {
                awardUserTimesJsonMap.put(activityAwardAndSettingBo.getAwardId(), awardUserTimesJson);
            }
        }
        // 发放A券
        for (ActivityAwardAndSettingBo a : activityAwardList) {
            if ("A".equals(a.getRemark())) {
                a.setRemark(a.getRemark());
                // 发放A奖品
                sendAwardService.sendCouponOrGoods(fansId, appId, a, activityEntity.getPayAuthId(), activityChannelId, true, fansActivityDTO.getExtJson());

                JSONObject awardUserTimesJson = awardUserTimesJsonMap.get(a.getAwardId());
                awardSettingService.updateAwardLimitCache(awardUserTimesJson, redisOutTime);
            }
            // 发放待激活卡券
            if ("C".equals(a.getRemark())) {
                sendAward(fansId, appId, activityChannelId, a, activityEntity.getEndTime(), agentInfoEntity);
            }
            if ("D".equals(a.getRemark())) {
                sendAward(fansId, appId, activityChannelId, a, activityEntity.getEndTime(), agentInfoEntity);
            }
            if ("E".equals(a.getRemark())) {
                sendAward(fansId, appId, activityChannelId, a, activityEntity.getEndTime(), agentInfoEntity);
            }
            if ("F".equals(a.getRemark())) {
                sendAward(fansId, appId, activityChannelId, a, activityEntity.getEndTime(), agentInfoEntity);
            }
        }

        //重新放置活动奖品配置缓存
        if (!activityAwardList.isEmpty()) {
            String activityAwardKey = String.format("%s%s:%s", Constants.REDIS_ACTIVITY.FILENAME, fansActivityDTO.getActivityId(), Constants.REDIS_ACTIVITY.AWARD);
            RedisUtil.set(activityAwardKey, activityAwardList, redisOutTime, TimeUnit.MILLISECONDS);
            log.info("活动奖品列表，修改奖品中的当前周期性领取次数数据，redisKey:{},redisValue:{},redisOutTime:{},TimeUnit:{}", activityAwardKey, JSONUtil.toJsonStr(activityAwardList), redisOutTime, "TimeUnit.MILLISECONDS");
        }

        //更新Redis中参与的次数
        ActivityUserTimesBO activityUserTimesBO = limitJson.getObject("activityUserTimesBO", ActivityUserTimesBO.class);
        if (ObjectUtils.isNotEmpty(activityUserTimesBO)){
            activitySettingService.updateRedisParticipateNum(limitJson.getString("currentTimesKey"), activityUserTimesBO, redisOutTime);
        }
        Boolean userJoinScoreValue = limitJson.getObject("userJoinScoreValue", Boolean.class);
        if (ObjectUtils.isNotEmpty(userJoinScoreValue)){
            RedisUtil.set(limitJson.getString("userJoinScoreKey"), userJoinScoreValue, redisOutTime, TimeUnit.MILLISECONDS);
        }

        return activityAwardService.toUserData(null);
    }

    private void sendAward(Long fansId, String appId, Long activityChannelId, ActivityAwardAndSettingBo activityAwardAndSettingBo, Date activityEndTime, AgentInfoEntity agentInfoEntity) {
        log.info("用户fansId：{},发放{}卡券", fansId, activityAwardAndSettingBo.getRemark());
        LambdaQueryWrapper<FansAwardEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FansAwardEntity::getFansId, fansId);
        queryWrapper.eq(FansAwardEntity::getAwardId, activityAwardAndSettingBo.getAwardId());
        queryWrapper.eq(FansAwardEntity::getAwardType, activityAwardAndSettingBo.getAwardType());
        queryWrapper.eq(FansAwardEntity::getState, Constants.FANS_AWARD_STATE.ACTIVATE);
        List<FansAwardEntity> fansAwards = fansAwardService.list(queryWrapper);
        if (null == fansAwards || fansAwards.isEmpty()) {
            sendAwardService.sendActivateAward(fansId, appId, activityAwardAndSettingBo.getAwardId(), activityAwardAndSettingBo.getAwardType(),
                    activityEndTime, activityAwardAndSettingBo.getRemark(), activityChannelId, null, null, agentInfoEntity);
        }
    }
}
